#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    class compare
    {
    public:
        bool operator()(const pair<string, int>& a, const pair<string, int>& b)
        {
            if (a.second == b.second)
            {
                return a.first < b.first;
            }
            return a.second > b.second;
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        vector<string>ret(k);
        map<string, int>mp;
        for (int i = 0; i < words.size(); i++)
        {
            mp[words[i]]++;
        }
        priority_queue<pair<string, int>, vector<pair<string, int>>, compare>heap;
        for (auto it = mp.begin(); it != mp.end(); it++)
        {
            heap.push(*it);
            if (heap.size() > k) heap.pop();
        }

        //reverse(ret.begin,ret.end());
        for (int i = k - 1; i >= 0; i--)
        {
            ret[i] = heap.top().first;
            heap.pop();
        }
        return ret;
    }
};